<template>
	<view class="m-flow-chart">
		<view v-if="status === 0" style="height: 100%;">
			<view class="cellTitle">
				<text>流程</text>
			</view>

			<scroll-view :scroll-y="true" :scroll-x="true" :style="{height: scrollHeight + 'px'}">
				<view style="height:100%;width:100%;padding-right:10px;">
					<m-time-line class="m-time-line" :tableData="approvalProcessList">
						<template #content="{ row }">
							<view>
								<view class="flex-box">
									<view class="mark">
										<view class="flex-box">
											<view>
												<view>
													<view>{{ row.nodeName }}</view>
												</view>
												<view style="color: #969799; font-size: 13px; margin-top: 4px;">
													<text v-if="row.type === 2">抄送通知</text>
													<text v-if="row.type === 1 && row.node.length === 1">1人审批</text>
													<text
														v-if="row.type === 1 && row.node.length > 1 && row.approvalType === 1">{{ getRealNum(row) }}人会签</text>
													<text
														v-if="row.type === 1 && row.node.length > 1 && row.approvalType === 0">{{ getRealNum(row) }}人或签</text>
												</view>
											</view>
										</view>
									</view>



									<scroll-view :scroll-y="false" :scroll-x="true" style="width: calc(100% - 80px);">
										<view class="x-f">

											<view class="x-start" style="padding-bottom: 3px;"
												v-for="(item, itemIndex) in row.node" :key="itemIndex">
												<view class="f-dc" style="min-width: 40px;">
													<view class="img" @click="toggleUserCheck(row, item)">
														<text>{{ cutStr(item.name) }}</text>
														<image class="sf"
															src="/uni_modules/mc-ui/static/image/success.png"
															v-if="!item.unJoin"></image>
													</view>
													<view class="ap-n">{{ item.name }}</view>
												</view>
												<view class="symbolIcon"
													v-if="itemIndex !== row.node.length - 1 && row.type === 1 && row.approvalType === 1">
													+</view>
												<view class="symbolIcon"
													v-if="itemIndex !== row.node.length - 1 && row.type === 2">+
												</view>
												<view class="symbolIcon"
													v-if="itemIndex !== row.node.length - 1 && row.type === 1 && row.approvalType === 0">
													/</view>
											</view>

										</view>
									</scroll-view>
								</view>
							</view>
						</template>
					</m-time-line>
				</view>
			</scroll-view>

		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, getCurrentInstance, nextTick } from 'vue';

	// 类型定义
	interface NodeItem {
		name : string;
		unJoin ?: boolean;
		[key : string] : any;
	}

	interface ApprovalProcessItem {
		type : number;
		approvalType : number;
		nodeName : string;
		node : NodeItem[];
		checked : boolean;
		data : any;
		showMore ?: boolean;
	}

	interface FormData {
		id : number;
		EmplName : string;
		C_Date : string;
		C_VarA : string;
		B_Date : string;
		C_VarE : string;
		C_VarB : string;
		C_Why : string;
	}

	// 直接定义组件props（原props.js内容迁移至此）
	const props = defineProps({
		// 根据实际业务补充原props.js中的属性定义
		option: {
			type: Object,
			default: () => ({
				nodeConfig: {
					childNode: {}
				}
			})
		},
		approveStr: {
			type: String,
			default: ''
		},
		// 可根据实际情况补充其他props属性
		title: {
			type: String,
			default: '流程图表'
		}
	});

	// 状态定义
	const showLoading = ref(false);
	const ifConfirm = ref(false);
	const showButton = ref(0);
	const isSubmit = ref(false);
	const personList = ref<any[]>([]);
	const approvalAgain = ref(false);
	const approvalActions = ref<any[]>([]);
	const selectApprovalData = ref('');
	const approvalList = ref<any[]>([]);
	const approvalProcessList = ref<ApprovalProcessItem[]>([]);
	const status = ref(-1);
	const creater = ref('');
	const createTime = ref('');
	const approvalID = ref(0);
	const level = ref(0);
	const finalResult = ref(0);
	const editRemark = ref(true);

	const form = ref<FormData>({
		id: 0,
		EmplName: '',
		C_Date: '',
		C_VarA: '',
		B_Date: '',
		C_VarE: '',
		C_VarB: '',
		C_Why: ''
	});

	// 递归处理审批流程数据
	const recursionFunc = (data : any) : ApprovalProcessItem[] => {
		const approvalProcessList : ApprovalProcessItem[] = [];

		const repeatConfig = (x : number, row : any) => {
			const processData : ApprovalProcessItem = {
				type: row.type,
				approvalType: row.examineMode === 1 ? 0 : 1,
				nodeName: row.nodeName,
				node: [],
				checked: true,
				data: row
			};

			if (row.settype === 7) {
				processData.node.push({
					name: `${row.examineEndDirectorLevel}级主管`
				});
			} else {
				processData.node = row.nodeUserList as NodeItem[];
			}

			approvalProcessList.push(processData);

			if (row.childNode) {
				repeatConfig(x + 1, row.childNode);
			}
		};

		if (data && data.nodeConfig) {
			data.nodeConfig.childNode && repeatConfig(0, data.nodeConfig.childNode);
		}

		return approvalProcessList;
	};

	// 获取审批流程
	const getApprovalProcess = (id : number) => {
		// 如果id=0，是发起审批状态
		if (id === 0) {
			status.value = 0;
			approvalProcessList.value = [];

			const approvalConfigdata = uni.$utils.deepClone(props.option);
			console.log(approvalConfigdata);

			let approvalProcessListTemp = recursionFunc(approvalConfigdata);
			let newApprovalProcessList : ApprovalProcessItem[] = [];

			if (props.approveStr) {
				try {
					newApprovalProcessList = recursionFunc(JSON.parse(props.approveStr));
				} catch (e) {
					console.error('解析approveStr失败:', e);
					newApprovalProcessList = [];
				}
			}

			// 处理审批流程列表数据
			for (const i in approvalProcessListTemp) {
				let w = 0;
				for (const j in newApprovalProcessList) {
					if (approvalProcessListTemp[i].nodeName === newApprovalProcessList[j].nodeName) {
						w = 1;
						approvalProcessListTemp[i].checked = true;

						for (const m in approvalProcessListTemp[i].node) {
							let v = 0;
							for (const n in newApprovalProcessList[j].node) {
								if (approvalProcessListTemp[i].node[m].name === newApprovalProcessList[j].node[n].name) {
									v = 1;
									approvalProcessListTemp[i].node[m].unJoin = false;
								}
							}
							if (!v) {
								approvalProcessListTemp[i].node[m].unJoin = true;
							}
						}
					}
				}

				if (!w) {
					if (newApprovalProcessList.length) {
						approvalProcessListTemp[i].checked = false;
					} else {
						for (const m in approvalProcessListTemp[i].node) {
							approvalProcessListTemp[i].node[m].unJoin = true;
						}
					}
				}
			}

			approvalProcessList.value = JSON.parse(JSON.stringify(approvalProcessListTemp));
			uni.$utils.hideLoading();
		}
	};

	// 获取部门名称
	const getBMName = (id : number) : string => {
		// 注意：bmlist需要在实际环境中定义或引入
		// @ts-ignore
		for (const i in bmlist) {
			// @ts-ignore
			if (bmlist[i].ClassID === id) {
				// @ts-ignore
				return bmlist[i].ClassName;
			}
		}
		return '';
	};

	// 获取职位名称
	const getZWName = (id : number) : string => {
		// 注意：zwlist需要在实际环境中定义或引入
		// @ts-ignore
		for (const i in zwlist) {
			// @ts-ignore
			if (zwlist[i].JobsID === id) {
				// @ts-ignore
				return zwlist[i].JobName;
			}
		}
		return '';
	};

	// 格式化日期
	const getFormatDate = (date : string) : string => {
		// @ts-ignore
		return APP.getFormatDate1('yyyy-MM-dd hh:mm:ss', new Date(date));
	};

	// 切换箭头显示状态
	const toggleArrow = (str : string) => {
		// 这里需要根据实际需求实现
		console.log('toggleArrow:', str);
	};

	// 获取实际数量
	const getRealNum = (row : ApprovalProcessItem) : number => {
		let t = 0;
		for (const i in row.node) {
			if (!row.node[i].unJoin) {
				t++;
			}
		}
		return t;
	};

	// 切换用户选择状态
	const toggleUserCheck = (row : ApprovalProcessItem, item : NodeItem) => {
		if (typeof item.unJoin === 'undefined') {
			item.unJoin = true;
			let x = 1;
			for (const i in row.node) {
				if (!row.node[i].unJoin) {
					x = 0;
				}
			}
			if (x === 1) {
				uni.$utils.msg('请至少选择一人');
				item.unJoin = false;
			}
		} else {
			item.unJoin = !item.unJoin;
			let x = 1;
			for (const i in row.node) {
				if (!row.node[i].unJoin) {
					x = 0;
				}
			}
			if (x === 1) {
				uni.$utils.msg('请至少选择一人');
				item.unJoin = !item.unJoin;
			}
		}
	};

	// 显示更多
	const showMore = (row : ApprovalProcessItem) => {
		row.showMore = !row.showMore;
	};

	// 截断字符串
	const cutStr = (str ?: string) : string => {
		if (!str) return '';
		return str.substring(str.length - 2);
	};

	// 预览图片
	const previewItemImage = (imgs : string, index : number) => {
		const array = imgs.split(',');
		// 实际项目中补充图片预览逻辑
		console.log('预览图片:', array, index);
	};
	const instance = getCurrentInstance() as any;

	let scrollHeight = ref(400);
	// 总盒子高度
	console.log(uni.$utils.getWindowInfo());

	const { windowHeight } = uni.$utils.getWindowInfo();
	function getScollHeightFun() {
		const query = uni.createSelectorQuery().in(instance.proxy);

		query.select('.m-time-line').boundingClientRect((data : any) => {
			console.log(data);
			let rowHeight = data.height <= +(windowHeight * 0.8 * 0.8) ? data.height : +(windowHeight * 0.8 * 0.8);

			scrollHeight.value = rowHeight;
		}).exec();


	}

	// 组件挂载时执行
	onMounted(() => {
		nextTick(() => {
			setTimeout(() => {
				getScollHeightFun();
			}, 300)
		})
		uni.$utils.showLoading();
		getApprovalProcess(0);
	});
</script>

<style lang="scss" scoped>
	@import url("./static/flowChart.scss");

	/* #ifndef MP-WEIXIN */
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	/* #endif */

	/* #ifdef MP-WEIXIN */
	view {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	/* #endif */



	/* flex相关 */
	.x-f {
		display: -webkit-flex;
		display: flex;
	}

	.m-flow-chart {
		height: 100%;

		.cellTitle {
			font-size: 24rpx;
			padding: 10px 15px;
			height: 40rpx;
		}

		.m-flow-chart--content {
			width: 100%;
			height: 100%;
			padding: 16px 0;

			.m-flow-chart--content-card {
				border-bottom: 1px solid #f7f7f7;
			}
		}
	}

	.symbolIcon {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: start;
		margin: 0 6px;
		color: #969799;
		padding-top: 7px;
	}

	::v-deep .m-time-line {
		width: 100%;
	}
</style>